<?php 

/**
 * 分类控制器
 */
class CategoryController extends CommonController{
	private $model;
	
	public function __init(){
	    $this->model = K('Category');
	}
	
    /**
     *  分类首页
     */
    public function index(){
    		$order = "cid ASC";
		$check = 0;
    		if (isset($_POST['sort_by_csort'])){    			
    			$order = 'csort DESC';
			$check = 1;
    		}
    		$data = M()->join($this->tableName('category'). " as c JOIN " . $this->tableName('type'). " as t ON c.tid=t.tid")->order("{$order}")->all();
    		$this->assign('check', $check);
    		$this->assign('data', Data::tree($data,'cname'));
    		$this->display(); 
    }
	
	// 添加分类
	public function add(){
		if (IS_POST){
			if (!$this->model->addData()){
				$this->error($this->model->error);
			}
			$this->success("添加分类成功", U('Index'));
		}
		$this->assign('typeData', K('Type')->all());
		$this->display();
	}
	
	// 修改分类
	public function edit(){
		if (IS_POST){
			if (!$this->model->editData()){
				$this->error($this->model->error);
			}
			$this->success("修改分类成功", U('Index'));
		}
		$cid = Q('get.cid', 0, 'intval');
		$this->assign('oldData', $this->model->where("cid={$cid}")->find());
		$this->assign('typeData', K('Type')->all());
		$this->display();
	}
	
	// 删除分类
	public function del(){
		$cid = Q('get.cid', 0, 'intval');
		// 判断是否有子类，如果有子类则不允许删除
		if ($this->model->where("pid={$cid}")->count() > 0){
			$this->error("请先删除其子类");
		}
		if (!$this->model->where("cid={$cid}")->delete()){
			$this->error($this->model->error);
		}
		$this->success("删除分类成功", U('Index'));
	}
 }
 
 
 
 
 
 
 
 
 
 
 


 ?>